package vendas.business;

import gminet.infra.business.BusinessException;
import gminet.infra.business.BusinessObject;
import gminet.infra.db.Transaction;
import gminet.infra.db.TransactionException;
import gminet.infra.toolkit.StringToolkit;

import java.sql.Connection;
import java.util.List;

import vendas.dao.UserDAO;
import vendas.dto.User;


public class AdministratorBusiness extends BusinessObject {

    public static User findByPK(int userId) throws BusinessException, TransactionException {

        User user = null;
        Transaction transaction = createTransaction();
        try {
            Connection conn = transaction.getConnection();
            user = UserDAO.findByPK(userId, conn);
        } finally {
            transaction.release();
        }
        return user;
    }

    public static void updateUser(User user) throws BusinessException, TransactionException {

        Transaction transaction = createTransaction();
        try {
            Connection conn = transaction.getConnection();
            UserDAO.update(user, conn);
            if (StringToolkit.isFill(user.getPassword())) {
                user.setPassword(LoginBusiness.crypt(user.getPassword()));
                UserDAO.updatePassword(user, conn);
            }
        } finally {
            transaction.release();
        }
    }

    public static List<User> listUsers() throws BusinessException, TransactionException {

        List<User> users = null;
        Transaction transaction = createTransaction();
        try {
            Connection conn = transaction.getConnection();
            users = UserDAO.findAll(conn);
        } catch (TransactionException te) {
            transaction.rollback();
            throw te;
        } finally {
            transaction.release();
        }
        return users;
    }

}
